package com.ls.mq.message;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.ls.mq.util.Toolkit;
import com.sun.istack.internal.Nullable;

public class Message implements Serializable {

	private static final long serialVersionUID = 8826578174431901434L;

	private Destination src;

	private Destination dest;

	private boolean isRequest = true;
	private boolean requestReply = false;
	/**
	 * 消息携带数据
	 */
	private String clazz;
	private String data;
	// private Object data;
	private boolean unicast;
	private String uuid;
	private Map<String, String> metaInfo;// 用于扩展添加新属性

	public Message(Destination dest, @Nullable Object data) {
		this(null, dest, data, true);
	}

	public Message(Destination src, Destination dest, Object data, boolean unicast) {
		this(src, dest, data, unicast, UUID.randomUUID().toString());
	}

	public Message(Destination src, Destination dest, Object data, boolean unicast, String uuid) {
		this.src = src;
		this.dest = dest;
		if (data != null) {
			this.clazz = data.getClass().getName();
			this.data = Toolkit.toJson(data);
		}
		this.unicast = unicast;
		this.uuid = uuid;
		metaInfo = new HashMap<>();
	}

	public Destination getSrc() {
		return src;
	}

	public void setSrc(Destination src) {
		this.src = src;
	}

	public Destination getDest() {
		return dest;
	}

	public void setDest(Destination dest) {
		this.dest = dest;
	}

	public boolean isUnicast() {
		return unicast;
	}

	public void setUnicast(boolean unicast) {
		this.unicast = unicast;
	}

	public Map<String, String> getMetaInfo() {
		return metaInfo;
	}

	public void setMetaInfo(Map<String, String> metaInfo) {
		this.metaInfo = metaInfo;
	}

	public boolean isRequest() {
		return isRequest;
	}

	public void setRequest(boolean isRequest) {
		this.isRequest = isRequest;
	}

	public String getUuid() {
		return uuid;
	}

	public void setUuid(String uuid) {
		this.uuid = uuid;
	}

	public String getClazz() {
		return clazz;
	}

	public void setClazz(String clazz) {
		this.clazz = clazz;
	}

	public void setData(String data) {
		this.data = data;
	}

	public String getData() {
		return data;
	}

	public boolean isRequestReply() {
		return requestReply;
	}

	public void setRequestReply(boolean requestReply) {
		this.requestReply = requestReply;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Object getDataObj() {
		String c = getClazz();
		Object obj = null;
		if (c != null) {
			Class clz;
			try {
				clz = Class.forName(c);
				String json = getData();
				obj = Toolkit.fromJson(json, clz);
			} catch (ClassNotFoundException e) {
			}
		}
		return obj;
	}

}
